<template>
	<view>
		<view class="search">
			<uni-search-bar @input="input" v-model="val" :radius="16" cancelButton="none" placeholder="搜索" />
		</view>
		<uni-list v-if="val.trim()">
			<uni-list-item :title="item.goods_name" @click="toDetail(item.goods_id)" clickable link v-for="item in searchResults" :key="item.goods_id" :ellipsis="1" />
		</uni-list>
		<view class="history-box" v-else>
			<view class="history-top">
				<text>搜索历史</text>
				<view v-if="isDel" class="del">
					<text @click="searchHistory=[]" style="margin-right: 24rpx;">全部删除</text>
					<text @click="isDel=false">取消</text>
				</view>
				<uni-icons v-else type="trash" size="20" @click="isDel=true"></uni-icons>
			</view>
			<view class="history-bottom">
				<view v-for="(item, i) in searchHistory" :key="i">
					<uni-tag :text="item" type="primary"  @click="tagClick(item, i)"></uni-tag>
					<uni-icons v-if="isDel" type="closeempty" size="14" class="tag"></uni-icons>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { searchResults } from '../../api/index.js'
	export default {
		data() {
			return {
				val: '',
				timer: null,
				searchResults: [],
				searchHistory: JSON.parse(uni.getStorageSync('kw')) || [],
				isDel: false
			};
		},
		methods: {
			input(e) {
				clearTimeout(this.timer)
				if (e.trim() === '') {
					return this.searchResults = []
				}
				this.timer = setTimeout(() => {
					this.searchResult()
					const index = this.searchHistory.findIndex(item => item === this.val)
					if (index >= 0) {
						this.searchHistory.splice(index, 1)
						this.searchHistory.unshift(this.val)
					} else {
						this.searchHistory.unshift(this.val)
					}
					uni.setStorageSync('kw', JSON.stringify(this.searchHistory))
				}, 300)
			},
			async searchResult() {
				const { message } = await searchResults({ query: this.val })
				this.searchResults = message
			},
			toDetail(id) {
				uni.navigateTo({
					url: `/subpkg/goods_detail/goods_detail?id=${id}`
				})
			},
			tagClick(val, index) {
				if (!this.isDel) {
					// 非删除状态点击
					uni.navigateTo({
						url: `/subpkg/goods_list/goods_list?query=${val}`
					})
				} else {
					this.searchHistory.splice(index, 1)
					uni.setStorageSync('kw', JSON.stringify(this.searchHistory))
				}
			}
		}
	}
</script>

<style scoped lang="scss">
.search {
	position: sticky;
	top: 0;
}
.history-box {
	.history-top {
		padding: 0 20rpx;
		height: 80rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border: 1px solid #ccc;
		.del {
			color: #000;
		}
	}
	.history-bottom {
		flex-wrap: wrap;
		display: flex;
		view {
			position: relative;
			margin-left: 30rpx;
			margin-top: 30rpx;
			.tag {
				position: absolute;
				top: -22rpx;
				right: -12rpx;
			}
		}
	}
}
</style>
